<?php
@session_start(); // maybe this is not the first line.
require_once(__PHY_LIB.'/func/db.func.php');

function passport_register($sAcct, $sPswd, $sNick) {
	$sQ = "INSERT INTO unit_user SET"
		. " acct='".addslashes($sAcct)."'"
		. ",pswd='".addslashes(md5($sPswd))."'"
		. ",nick='".addslashes($sNick)."'";
	if (0 < db_write($sQ)) {
		return true;
	}
	else {
		return -1; // same acct.
	}
}

function passport_login($sAcct, $sPswd, $bLong=false){
	$sQ = "SELECT user_id,acct,pswd,nick"
		. " FROM unit_user"
		. " WHERE acct='".addslashes($sAcct)."'";
	$rUser = db_assoc($sQ);
	if ($rUser && md5($sPswd) == $rUser['pswd']) {
		/// set cookies ///
		$nExpire = $bLong ? (time() + 86400*30) : null;
		setcookie('user_id', $rUser['user_id'], $nExpire, '/'); $_COOKIE['user_id'] = $rUser['user_id'];
		setcookie('acct', $rUser['acct'], $nExpire, '/'); $_COOKIE['acct'] = $rUser['acct'];
		setcookie('nick', $rUser['nick'], $nExpire, '/'); $_COOKIE['nick'] = $rUser['nick'];
		/// unit_user ///
		$sQ = "UPDATE unit_user SET last_login=NOW() WHERE user_id='{$rUser['user_id']}'";
		db_write($sQ);
		/// log_action ///
		$sQ = "INSERT INTO log_action SET"
			. " user_id='{$rUser['user_id']}'"
			. ",add_time=NOW()"
			. ",page_id=0,target_class='',target_id=0" //todo
			. ",method='Login'";
		db_write($sQ);
		return $rUser;
	}
	else {
		return false;
	}
}

function passport_password($sAcct, $sOldPswd, $sNewPswd)
{
	$sQ = "SELECT acct,pswd"
		. " FROM unit_user"
		. " WHERE acct='".addslashes($sAcct)."'";
	$rUser = db_assoc($sQ);
	if ($rUser && md5($sOldPswd) == $rUser['pswd']) {
		$sQ = "UPDATE unit_user"
			. " SET pswd='".addslashes(md5($sNewPswd))."'"
			. " WHERE acct='".addslashes($sAcct)."'";
		if (0 < db_write($sQ)) { return true; }
		else { return false; }
	}
	else {
		return false;
	}
}

function passport_logout()
{
	setcookie('user_id', '', time()-86400, '/'); unset($_COOKIE['user_id']);
	setcookie('acct', '', time()-86400, '/'); unset($_COOKIE['acct']);
	setcookie('nick', '', time()-86400, '/'); unset($_COOKIE['nick']);
	return true;
}

function passport_islogged()
{
	if (isset($_COOKIE['user_id'])) {
		$rUser = array(
			'user_id' => isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : false,
			'acct' => isset($_COOKIE['acct']) ? $_COOKIE['acct'] : false,
			'nick' => isset($_COOKIE['nick']) ? $_COOKIE['nick'] : false,
		);
		return $rUser;
	}
	else {
		return false;
	}
}
?>
